#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import COOPGIS_Ajax, COOPGIS_FormMisc, COOPGIS_FormAssembly, COOPGIS_FormGeography, COOPGIS_GPS, COOPGIS_Misc
import COOPGIS_DynamicTemplate, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import COOPGIS_FormStaker
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms




from django.db import transaction


def AssemblyEditor(request, StakerWorkOrderid):
    ApplicationName=djangoproject.settings.COOPGISStakerApplicationName
    UserNameOrIPAddress, DefaultMap=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=True, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName) 
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName + 'AssemblyEditor', DefaultMap)
    if(not applicationPermission):
        MapFileName, LayerName=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=True, ApplicationName=ApplicationName)
        OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(None, None)      
        t = loader.get_template('/opt/coopgis/djangoproject/templates/stakerassemblyeditor.html')
        c = Context({'OpenLayersZoom': OpenLayersZoom, 'AssemblyEditor': assemblyEditorForm,
                     'MapFileName': MapFileName, 'LayerName': LayerName, 'LoginStatus':LoginStatus})
        return HttpResponse(t.render(c))
    try:
        stakerWorkOrder=StakerWorkOrder.objects.filter(id__exact=int(StakerWorkOrderid))[0]
    except:
        raise(Exception('Invalid Staker Work Order ID'))
    StakerWorkOrderMessage=str(stakerWorkOrder.id) + ':  ' + stakerWorkOrder.Name 
    SelectionStation=SelectionSpan=GPSStatus2=''
    COOPGIS_FormGeography.GetAndSetDefaultMap(form, ApplicationName, UserNameOrIPAddress)
    SelectionStation, SelectionSpan, GPSStatus = COOPGIS_FormGeography.SetSelectionStationAndSpan(form)
    SelectionStation, SelectionSpan, GPSStatus2=COOPGIS_FormGeography.CreateStation(form, SelectionStation, SelectionSpan, UserNameOrIPAddress)
    SelectionSpan=COOPGIS_FormGeography.CreateSpan(form, SelectionStation, SelectionSpan, UserNameOrIPAddress)
    COOPGIS_FormGeography.UpdateStationComment(form, SelectionStation, UserNameOrIPAddress)
    COOPGIS_FormGeography.UpdateSpanComment(form, SelectionSpan, UserNameOrIPAddress)
    GPSStatus3, SelectionStation = COOPGIS_FormGeography.MoveStation(form, SelectionStation, UserNameOrIPAddress)
    OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(SelectionStation, SelectionSpan)  #Get the Zoom before the span is deleted so area is not left on this refresh    
    COOPGIS_FormGeography.DeleteStation(form, SelectionStation, UserNameOrIPAddress)
    COOPGIS_FormGeography.DeleteSpan(form, SelectionSpan, UserNameOrIPAddress)
    AssemblySelectionStation, AssemblySelectionSpan=COOPGIS_FormAssembly.GetCurrentOrPreviousSelection(form, SelectionStation, SelectionSpan)
    NumberOfStationAssembliesListedOnForm=COOPGIS_FormAssembly.GetNumberOfStationAssembliesListedOnForm(SelectionStation)
    NumberOfSpanAssembliesListedOnForm=COOPGIS_FormAssembly.GetNumberOfSpanAssembliesListedOnForm(SelectionSpan)
    for assemblyFormNumber in range(0, NumberOfStationAssembliesListedOnForm + 1):
        COOPGIS_FormAssembly.ProcessStationAssembly(form, assemblyFormNumber, AssemblySelectionStation, UserNameOrIPAddress, stakerWorkOrder=stakerWorkOrder)
    for assemblyFormNumber in range(0, NumberOfSpanAssembliesListedOnForm + 1):
        COOPGIS_FormAssembly.ProcessSpanAssembly(form, assemblyFormNumber, AssemblySelectionSpan, UserNameOrIPAddress, stakerWorkOrder=stakerWorkOrder)
    if(SelectionStation or SelectionSpan):
        SelectionStation, SelectionSpan, GPSStatus = COOPGIS_FormGeography.SetSelectionStationAndSpan(form)
        OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(SelectionStation, SelectionSpan)  #if a station is moved, move with it on the current postback
    else:  #Attempt to zoom in to the general area of the staker work order
        StakerAssemblies=Assembly.objects.filter(StakerWorkOrder=stakerWorkOrder)
        if(StakerAssemblies):
            OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(StakerAssemblies[0].Station, StakerAssemblies[0].Span, 21)
    COOPGIS_FormAssembly.ProcessSplitSpan(form, AssemblySelectionSpan, UserNameOrIPAddress, stakerWorkOrder)
    try:
        StakerRecipeReportIndicator=bool(form.data['StakerRecipeReportIndicator'] == 'on')
    except:
        StakerRecipeReportIndicator=False
    if(StakerRecipeReportIndicator):
        StakerRecipeReport=stakerWorkOrder.GetRecipeReport()
    else:
        StakerRecipeReport=''
    #Now the Form Has been processed, it needs to be dynamically rebuilt to reflect the new number of Assemblies at the station and span
    NumberOfStationAssembliesListedOnForm=COOPGIS_FormAssembly.GetNumberOfStationAssembliesListedOnForm(SelectionStation)
    NumberOfSpanAssembliesListedOnForm=COOPGIS_FormAssembly.GetNumberOfSpanAssembliesListedOnForm(SelectionSpan)
    NewForm=COOPGIS_FormMisc.BuildForm(request, ApplicationName + 'AssemblyEditor', DefaultMap, station=SelectionStation, span=SelectionSpan)
    NewForm=COOPGIS_FormAssembly.CopyPreviousFormInformation(form, NewForm)
    form=NewForm
    COOPGIS_FormMisc.PopulateMiscFormFields(form)
    COOPGIS_FormAssembly.PopulateStationAssemblies(form, SelectionStation, NumberOfStationAssembliesListedOnForm, InstallStatusName='Install')
    COOPGIS_FormAssembly.PopulateSpanAssemblies(form, SelectionSpan, NumberOfSpanAssembliesListedOnForm, InstallStatusName='Install')
    COOPGIS_Misc.UpdateSelection(SelectionStation, SelectionSpan, UserNameOrIPAddress)
    SpanAngleTable=COOPGIS_Misc.GetSpanAngleTable(SelectionStation)
    COOPGIS_DynamicTemplate.UpdateStakerAssemblyEditorTemplate(NumberOfStationAssembliesListedOnForm, NumberOfSpanAssembliesListedOnForm, UserNameOrIPAddress, stakerWorkOrder)
    ShowSummaryIndicator, StakerWorkOrderSummary=COOPGIS_FormStaker.ProcessStakerSummary(form, stakerWorkOrder)
    MapFileName, LayerName=COOPGIS_Misc.GenerateDynamicMapFile(ApplicationName, UserNameOrIPAddress, stakerWorkOrder) 
    t = loader.get_template('/opt/coopgis/djangoproject/templates/stakerassemblyeditor' + UserNameOrIPAddress + '.html')
    c = Context({'OpenLayersZoom': OpenLayersZoom, 'form': form,
                 'LoginStatus':LoginStatus, 'MapFileName': MapFileName, 'LayerName': LayerName,
                 'GPSStatus':GPSStatus, 'GPSStatus2': GPSStatus2, 'GPSStatus3': GPSStatus3, 'StakerWorkOrderMessage': StakerWorkOrderMessage,
                 'StakerWorkOrderSummary': StakerWorkOrderSummary, 'ShowSummaryIndicator': ShowSummaryIndicator,
                 'SpanAngleTable': SpanAngleTable, 'StakerRecipeReport': StakerRecipeReport})
    return HttpResponse(t.render(c))

def AssemblyEditorSelectStationandSpan(SelectGPSIndicator, SelectStationid, SelectTagNumber, SelectSpanid, UserNameOrIPAddress):
    SelectionStation=None
    SelectionSpan=None
    GPSStatus=''
    if(SelectGPSIndicator):
         SelectionStation, SelectionSpan, GPSStatus=COOPGIS_GPS.GetNearbyStationandSpanFromGPS()
         try:
             SelectStationid=SelectionStation.id
         except:
             SelectStationid = None
         try:
             SelectSpanid=SelectionSpan.id
         except: 
             SelectSpanid=None
         SelectionStationTagNumber = None
    elif(SelectStationid):
        try:
            SelectionStation=Station.objects.filter(id__exact=SelectStationid)[0]
        except:
            SelectionStation = None
        if(SelectionStation):
            SelectTagNumber=''
    elif(SelectTagNumber):
        try:
            try:
                SelectionStation=Assembly.objects.all().filter(TagNumber__exact=SelectTagNumber)[0].Station
            except:
                SelectionStation=Assembly.objects.all().filter(TagNumber__startswith=SelectTagNumber)[0].Station
        except:
            SelectionStation = None
        if(SelectionStation):
            SelectionStationid=''
    if(not SelectionSpan):
        try:
            SelectionSpan=Span.objects.filter(id__exact=SelectSpanid)[0]
        except:
            SelectionSpan = None
    try:
        SelectSpanid=SelectionSpan.id
    except:
        SelectSpanid=''
    if(not SelectionStation):
        SelectTagNumber = ''
        SelectStationid = ''
    return SelectionStation, SelectionSpan, SelectStationid, SelectTagNumber, SelectSpanid, GPSStatus       
      
 

def AssemblyEditorUpdateHighlight(station, span, UserNameOrIPAddress):  
    SelectionPoint.objects.filter(UserName__exact=UserNameOrIPAddress).delete()
    if(station):
        New=SelectionPoint()
        New.Point=station.Point
        New.UserName=UserNameOrIPAddress
        New.save()
    SelectionLine.objects.filter(UserName__exact=UserNameOrIPAddress).delete()
    if(span):
        New=SelectionLine()
        New.Line=span.Line
        New.UserName=UserNameOrIPAddress
        New.save()
        



